package com.jar.exercise.网络编程.TCP连接.客服端和服务端;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 例子：转换大小写
 * TCP连接，客户端发送信息，服务器进行转换大写并返回给客户端
 * 都是文本，建议使用字符流
 */
class Server {

	public static void main(String[] args) throws IOException {
		//创建数据包对象
		ServerSocket serverSocket = new ServerSocket(12000);
		//读取信息到socket流中
		Socket socket = serverSocket.accept();
		//创建字符输入流，读取信息
		BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));

		//创建一个字符输出流，把转换的大写信息写进去，发送给客户端
		PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);
		String line;
		while ((line = br.readLine()) != null) {
			System.out.println(line);
			pw.println(line.toUpperCase());
		}
		socket.close();
		serverSocket.close();
	}
}

class Client {
	public static void main(String[] args) throws IOException {
		//创建数据包对象
		Socket socket = new Socket("192.168.234.1", 12000);
		//创建键盘录入对象
		BufferedReader sc = new BufferedReader(new InputStreamReader(System.in));
		//创建socket写入流,将键盘录入的东西写到socket流中
		PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);
		//创建socket读取流，将服务器返回的消息读取出来
		BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));

		String line;

		while ((line = sc.readLine()) != null) {
			if ("exit".equals(line)) {
				break;
			}
			//写进去
			pw.println(line);
			String s = br.readLine();
			System.out.println("服务器：" + s);
		}
		sc.close();
		socket.close();
	}

}
